<?php

namespace Module\Admin;

use Manager\User as Manager;
use W3\Html;
use W3\Exception;

!defined('W3_ROOT_DIR') AND exit;

/**
 * 成员列表组件
 *
 * @author edikud
 * @date 2022/10/22
 * @copyright Copyright (c) 2022 W3 (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */
class User extends Manager
{
    /**
     * 初始化
     *
     * @access protected
     * @return void
     */
    protected function init()
    {
        # 必须为管理员以上权限
        $this->auth->check('admin');
		
		# 定义变量默认数据
        $this->parameter([

			# 设置主体
			'main' => 'admin.user',
			
			# 分页大小
		    'pageSize'=>20,
			
			# 操作列表
		    'operate'=> [
			    'selectall'=>[
				    'name'=>__('全选'),
					'data-selectall'
				], 
				'delete'=>[
				    'name'=>__('删除'),
					'data-confirm'=>__('删除不可恢复，确定删除？'),
					'href'=>$this->adminUrl('user/delete', false)
				]
			],
			
			# 操作列表
		    'tabs'=> [],
			
			# 按钮列表
		    'buttons'=> []
			
		], true);
	}
	
    /**
     * 绑定动作
     *
     * @access public
     * @return void
     */
    public function action()
    {
		$this->on(!$this->request->action || $this->request->is('action=index'))->index();
		$this->on($this->request->is('action=edit'))->edit();
		$this->on($this->request->isPost() && $this->request->is('action=edit'))->update();
		$this->on($this->request->is('action=add'))->edit();
		$this->on($this->request->isPost() && $this->request->is('action=add'))->add();
		$this->on($this->request->isPost() && $this->request->is('action=delete'))->delete();
    }
	
    public function index()
    {
        /** users查询 */
        $select = $this->db
			->select()
		    ->from('table.users');

		/** 查询 */
        if (NULL != ($keywords = $this->request->filter('search')->keywords)) {
			$search = in_array($this->request->search, ['uid', 'name', 'mail', 'group', 'ip']) 
			    ? $this->request->search 
			    : 'name';
			'ip' == $search && $keywords = ip2long($keywords);
			$select->where("table.users.{$search} LIKE ?", '%' . $keywords . '%');
        }
		
		/** 计算数目 */
		$total = $select->count();
		$page = $this->request->get('page', 1);
		$pageUrl = $this->request->makeUrl('page=%page%');

        /** 提交查询 */
        $select
		    ->order('table.users.uid', 'ASC')
            ->page($page, $this->parameter->pageSize)
			->get([$this, 'push']);
		
		$this->parameter([
			
			# 当前页数
			'page'         => $page,
			
			# 内容总数 
			'total'        => $total,
			
			# 页面Url 
			'pageUrl'      => $pageUrl
			
		]);

		# 版面布局
		$this->layout->set($this->tabs(false), 'top');
		$this->layout->set($this->userList(), 'body');
		$this->layout->set($this->pagination(false), 'bottom');

		$this->view();
    }

    public function userList()
    {
		$form = Html::form()
		    ->method('get')
			->addClass('mb-3');
		
		$search = Html::select(
		    'search', 
		    [
			    'uid'=>__('用户 ID'), 
				'name'=>__('用户名'), 
				'mail'=>__('Email'), 
				'group'=>__('用户组'), 
				'ip'=>__('创建 IP')
			],
			$this->request->get('search', 'name')
		)->addClass('mb-2');
		
		$form->set($search);
		
		$keywords = Html::search('keywords', htmlspecialchars($this->request->keywords))->placeholder(__('请输入关键字'));
		
        if (!empty($_GET)){
			$keywords
			    ->reset
				->show()
				->title(__('取消筛选'))
				->href($this->adminUrl('user', false));
	    }
		
		$form->set($keywords);

		$html = $form->render();

        if ($this->have()) {
			$table = Html::table();
			$table->thead->preppend($this->operate(false));
			$table->thead->preppend('
                <colgroup>
				    <col width="3%" />
					<col width="3%" />
                    <col width="15%" />
					<col width="15%" />
					<col width="15%" />
					<col />
                </colgroup>
			');
			$table->head([
			    '',
				'',
			    __('用户名'),
				__('昵称'),
			    __('电子邮件'),
				__('用户组'),
			]);
			
			while ($this->next()){
			    $table->body([
				    Html::checkbox('uid', [$this->uid => '']),
					'<a class="badge badge-md badge-pill badge-primary-soft mr-2" href="'.$this->adminUrl('post', 'uid=' . $this->uid, false). '">'. $this->postNum .'</a>',
				    '<a href="' .$this->adminUrl('user/edit', 'uid=' . $this->uid, false) . '">'.$this->name.'</a>&nbsp;&nbsp;<a target="_blank" class="text-muted text-md" href="'.$this->permalink.'"><svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-link-2"><path d="M15 7h3a5 5 0 0 1 5 5 5 5 0 0 1-5 5h-3m-6 0H6a5 5 0 0 1-5-5 5 5 0 0 1 5-5h3"></path><line x1="8" y1="12" x2="16" y2="12"></line></svg></a>',
					$this->domainPath ? '<a href="'.$this->domainPath. '">'. $this->nickName .'</a>' : $this->nickName,
					$this->mail ? '<a href="mailto:'.$this->mail.'">'.$this->mail.'</a>' : __('暂无'),
					$this->auth->group($this->group)
				]);
			}

			$html .= $table->wrap(Html::form()->removeClass('w3-form'))->render();
		}

		return $html;
	}

    public function edit()
    {
        if ($this->request->uid) {

            /** 按tag查询 */
            $this->db
				->select()
		        ->from('table.users')
                ->where('table.users.uid = ?', $this->request->filter('int')->uid)
			    ->limit(1)
			    ->fetch([$this, 'push']);

            if (!$this->have()) {
				
				throw new Exception(__('用户不存在'), 404);
            }
        }
		
        /** 更新模式 */
        if ($this->uid) {
			$this->parameter->title = __('编辑用户: %s', [$this->name]);
        } else {
			$this->parameter->title = __('增加用户');
		}
		
		/** 输出内容 */
		$this->layout->set($this->form(), 'body');
		
		$this->view();
    }

    public function add()
    {
		$form = $this->form();
			
		/** 验证格式 */
        if ($form->validate()) {
            $this->goBack();
        }

		/** 取出数据 */
        $user = $this->request->from(array_keys($form->getInputs()));
        $user['nickName'] = empty($user['nickName']) ? $user['name'] : $user['nickName'];
        $user['created'] = $this->config->time;

		$uid = $this->addUser($user);

        $this->db
		    ->select()
		    ->from('table.users')
			->where('table.users.uid = ?', $uid)
			->fetch([$this, 'push']);
			
        /** 提示信息 */
        $this->notice(__('用户 %s 增加成功', [$this->nickName]));
		
		$this->redirect($this->adminUrl('user', false));
	}

    public function update()
    {
		/** 构建表格 */
		$form = $this->form();
			
		/** 验证格式 */
        if ($form->validate()) {
            $this->goBack();
        }
				
		/** 取出数据 */
        $user = $this->request->from(array_keys($form->getInputs()));
        $user['nickName'] = empty($user['nickName']) ? $this->name : $user['nickName'];
				
		/** 不允许修改用户名 */
		unset($user['name']);
				
        if (empty($user['password'])) {
            unset($user['password']);
        }

		$this->updateUser($this->uid, $user);

		// 获取页面偏移的URL Query
        $count = $this->db
		    ->select()
		    ->from('table.users')
			->where('table.users.uid > ?', $this->uid)
			->count() + 1;

        /** 提示信息 */
        $this->notice(__('用户 %s 更新成功', [$this->name]));
		
		$this->redirect($this->adminUrl('user', 'page=' . ceil($count / $this->parameter->pageSize), false));
	}

    public function delete()
    {
        $uids = $this->request->filter('int')->getArray('uid');
        $deleteCount = 0;

        foreach ($uids as $uid) 
		{
		    if($this->deleteUser($uid)){ 
				$deleteCount++;
			}
        }
			
        /** 设置提示信息 */
        $this->notice(
		    $deleteCount > 0 
			? __('用户已经删除') 
			: __('没有用户被删除'), $deleteCount > 0 ? 'success' : 'notice'
		);
		
		$this->goBack();
	}
	
    /**
     * 发布文章数
     *
     * @return integer
     * @throws Db\Exception
     */
    protected function ___postNum(): int
    {
        return $this->db->select(['COUNT(*)' => 'num'])
		    ->from('table.contents')
			->where('table.contents.type = ?', 'post')
			->where('table.contents.status = ?', 'publish')
			->where('table.contents.uid = ?', $this->uid)
            ->object()
			->num;
    }
}
